﻿using Admin.NET.Core.Service;
using Admin.NET.Application.Const;
using Admin.NET.Application.Entity;
using Microsoft.AspNetCore.Http;
using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Excel;
using Furion.DatabaseAccessor;
namespace Admin.NET.Application;
/// <summary>
/// 班级服务
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class BanjiService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Banji> _rep;
    private readonly SqlSugarRepository<Teacher> _teacherRep;
    private readonly SqlSugarRepository<SysFile> _fileRep;
    public BanjiService(SqlSugarRepository<Banji> rep,
        SqlSugarRepository<Teacher> teacherRep,
        SqlSugarRepository<SysFile> fileRep)
    {
        _rep = rep;
        _teacherRep = teacherRep;
        _fileRep = fileRep;

    }

    /// <summary>
    /// 分页查询班级
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]
    public async Task<SqlSugarPagedList<BanjiOutput>> Page(BanjiInput input)
    {
        var query = _rep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey), u =>
                u.BianHao.Contains(input.SearchKey.Trim())
                || u.Name.Contains(input.SearchKey.Trim())
                || u.Beizhu.Contains(input.SearchKey.Trim())
            )
            .WhereIF(!string.IsNullOrWhiteSpace(input.BianHao), u => u.BianHao.Contains(input.BianHao.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Name), u => u.Name.Contains(input.Name.Trim()))
            .WhereIF(input.BzrId>0, u => u.BzrId == input.BzrId)
            .WhereIF(input.Xueduan>0, u => u.Xueduan == input.Xueduan)
            .WhereIF(input.Ji>0, u => u.Ji == input.Ji)
            .WhereIF(input.Bh>0, u => u.Bh == input.Bh)
            .WhereIF(!string.IsNullOrWhiteSpace(input.Beizhu), u => u.Beizhu.Contains(input.Beizhu.Trim()))
            //处理外键和TreeSelector相关字段的连接
            .LeftJoin<Teacher>((u, bzrid) => u.BzrId == bzrid.Id )
            .OrderByDescending(u => u.BianHao)
            .Select((u, bzrid) => new BanjiOutput
            {
                Id = u.Id,
                BianHao = u.BianHao,
                Name = u.Name,
                BzrId = u.BzrId, 
                BzrIdName = bzrid.Name,
                Xueduan = u.Xueduan,
                Ji = u.Ji,
                Bh = u.Bh,
                Beizhu = u.Beizhu,
                IsGraduated = u.IsGraduated,
                CreateUserName = u.CreateUserName,
                UpdateUserName = u.UpdateUserName,
            });
        return await query.ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加班级
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    public async Task<long> Add(AddBanjiInput input)
    {
        var entity = input.Adapt<Banji>();
        await _rep.InsertAsync(entity);
        return entity.Id;
    }

    /// <summary>
    /// 删除班级
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    public async Task Delete(DeleteBanjiInput input)
    {
        var entity = await _rep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _rep.FakeDeleteAsync(entity);   //假删除
        //await _rep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 更新班级
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    public async Task Update(UpdateBanjiInput input)
    {
        var entity = input.Adapt<Banji>();
        await _rep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 获取班级
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    public async Task<Banji> Detail([FromQuery] QueryByIdBanjiInput input)
    {
        return await _rep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 获取班级列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "List")]
    public async Task<List<BanjiOutput>> List([FromQuery] BanjiInput input)
    {
        return await _rep.AsQueryable().Select<BanjiOutput>().ToListAsync();
    }

    /// <summary>
    /// 获取班主任列表
    /// </summary>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "TeacherBzrIdDropdown"), HttpGet]
    public async Task<dynamic> TeacherBzrIdDropdown()
    {
        return await _rep.Context.Queryable<Teacher>()
                .Select(u => new
                {
                    Label = u.Name,
                    Value = u.Id
                }
                ).ToListAsync();
    }

    /// <summary>
    /// 获取班级导入列表预览
    /// </summary>
    /// <param name="fileId">文件Id</param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "ImportPreview")]
    public async Task<List<BanjiImportDto>> ImportPreview([FromQuery] long fileId)
    {
        var file = _fileRep.GetById(fileId);
        var filePath = App.WebHostEnvironment.WebRootPath;
        filePath = System.IO.Path.Combine(filePath, file.FilePath);
        filePath = System.IO.Path.Combine(filePath, file.Id.ToString());
        filePath += file.Suffix;

        IImporter importer = new ExcelImporter();
        var res = await importer.Import<BanjiImportDto>(filePath);
        var data = new List<BanjiImportDto>();
        foreach (var item in res.Data)
        {
            var bj = new BanjiImportDto
            {
                BianHao = item.BianHao,
                Name = item.Name,
                Xueduan = item.Xueduan,
                Ji = item.Ji,
                Bh = item.Bh,
                BzrName = item.BzrName,
                IsGraduated = item.IsGraduated,
                Msg = item.Msg,
            };
            if (bj.BianHao.IsNullOrEmpty())
            {
                bj.BianHao = string.Format("{0}{1}",bj.Ji,bj.Bh.ToString().PadLeft(2,'0'));
            }
            if (bj.Name.IsNullOrEmpty())
            {
                bj.Name = string.Format("{0}({1})", bj.Ji, bj.Bh.ToString().PadLeft(2, '0'));
            }
            data.Add(bj);
        }
        return data;
    }

    /// <summary>
    /// 班级导入
    /// </summary>
    /// <param name="banjiListImportDto">导入数据表</param>
    /// <returns></returns>
    [HttpPost]
    [UnitOfWork]
    [ApiDescriptionSettings(Name = "Import")]
    public async Task Import(List<BanjiImportDto> banjiListImportDto)
    {
        foreach (var item in banjiListImportDto)
        {
            var bzrName = item.BzrName;
            var bzr = await this._teacherRep.AsQueryable().Where(p => p.Name == bzrName).FirstAsync();

            if (item.BianHao.IsNullOrEmpty())
            {
                item.BianHao = string.Format("{0}{1}", item.Ji, item.Bh.ToString().PadLeft(2, '0'));
            }
            if (item.Name.IsNullOrEmpty())
            {
                item.Name = string.Format("{0}({1})", item.Ji, item.Bh.ToString().PadLeft(2, '0'));
            }
            var bj = await _rep.AsQueryable().Where(p => p.BianHao == item.BianHao).FirstAsync();
            if(bj == null)
            {
                bj = new Banji();
                bj.BianHao = item.BianHao;
                bj.Name = item.Name;
                bj.IsGraduated = false;
                bj.Xueduan = item.Xueduan;
                bj.Ji = item.Ji;
                bj.Bh = item.Bh;

                if (bzr != null)
                {
                    bj.BzrId = bzr.Id;
                }
                await _rep.InsertAsync(bj);
            }
            else
            {
                bj.Name = item.Name;
                if (bzr != null)
                {
                    bj.BzrId = bzr.Id;
                }
                await _rep.UpdateAsync(bj);
            }            
        }
    }

    /// <summary>
    /// 获取级列表
    /// </summary>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "BanjiJiDropdown"), HttpGet]
    public async Task<dynamic> BanjiJiDropdown()
    {
        return await _rep.Context.Queryable<Banji>()
                .Where(p => p.IsGraduated == false)
                .Distinct()
                .Select(u => new
                {
                    Label = u.Ji,
                    Value = u.Ji
                }
                ).ToListAsync();
    }
}

